<template>
  <div :style="{ height: wrapHeight }" class="overflow-hidden relative box-border h-full" aria-label="歌词">
    <Karaoke
      ref="karaokeRef"
      :font-size="lyricStyle.fontSize"
      :active-font-size="lyricStyle.activeFontSize"
      :lrc-lyric="lrcLyric"
      :ass-lyric="assLyric"
      :lyric="lyric"
      :current-time="playView.currentTime"
      :line-height="lyricStyle.lineHeight"
      :base-color="lyricStyle.baseColor"
      :highlight-color="lyricStyle.highlightColor"
      :active-color="lyricStyle.activeColor"
      @scaleLineClick="handleLyricClick"
    />
  </div>
</template>

<script setup lang="ts" name="star-lyric">
import { onMounted, toRefs } from "vue";
import { watch } from "vue";
import { onUnmounted, useTemplateRef } from "vue";
import { withDefaults, computed } from "vue";
import { useEventListener, useWindowSize } from "@vueuse/core";
import { useAudio } from "@/hooks/useAudio";
import { Karaoke } from "@/package/ass-parse";
import useIsDark from "@/hooks/useIsDark";
const { isDark } = useIsDark();
const { width } = useWindowSize();
const props = withDefaults(
  defineProps<{
    height?: string;
  }>(),
  {}
);
const { info, playView, audio: audioStore } = useAudio();
const { height } = toRefs(props);
const karaokeRef = useTemplateRef("karaokeRef");

const wrapHeight = computed(() => {
  return height.value;
});
const audio = computed(() => {
  return audioStore.value.ad;
});

const lyric = computed(() => {
  const { lyric } = info.value.dmtUrl || {};
  return lyric;
});

const lrcLyric = computed(() => {
  const { lrc } = info.value.dmtUrl || {};
  return lrc;
});

const assLyric = computed(() => {
  const { assLyric } = info.value.dmtUrl || {};

  return assLyric;
});

const lyricStyle = computed(() => {
  const style = {
    baseColor: "#64748b",
    scaleLineColor: "#444",
    highlightColor: "#be123c",
    activeColor: "#334155",
    fontSize: 18,
    activeFontSize: 22,
    lineHeight: 2.2,
  };
  if (width.value > 768) {
    style.fontSize = 28;
    style.activeFontSize = 32;
    style.lineHeight = 2.4;
  }

  if (width.value > 976) {
    style.fontSize = 32;
    style.activeFontSize = 36;
    style.lineHeight = 2.6;
  }

  if (isDark.value) {
    style.baseColor = "#d1d5db";
    style.activeColor = "#f9fafb";
    style.highlightColor = "#ff4757";
  }

  return style;
});

const cleanup = useEventListener("keypress", (e) => {
  e.preventDefault();
});

onMounted(() => {
  audio.value.removeEventListener("ended", ended);
  audio.value.addEventListener("ended", ended);
});

onUnmounted(() => {
  audio.value.removeEventListener("ended", ended);
  cleanup();
});
function ended() {
  karaokeRef.value?.resetCurrentIndex();
}

function handleLyricClick(time: number) {
  if (time === null) return;
  audio.value.currentTime = time;
}
watch(info, () => {
  ended();
});
</script>
